import Fetcher from "@zxy-cn/fetcher"
import employeeAuthorizationStore from "../store/AuthorizationStore";
import {preHandleObjectWithDateTimeParser} from "../utils/Date";
const fetcher = new Fetcher(process.env.REACT_APP_SERVER_URL??"")

fetcher.addRequestInterceptor(request => {
    request.headers.append("timezone",Intl.DateTimeFormat().resolvedOptions().timeZone)
    return request
})

fetcher.addRequestInterceptor(request => {
    let authorization = employeeAuthorizationStore.authorization
    if (authorization) {
        request.headers.append("Authorization", authorization)
    }
    return request
})


fetcher.addResponseInterceptor(response => {
    const data= response.data as any
    preHandleObjectWithDateTimeParser(data)
})

fetcher.addErrorInterceptor(error => {
    if (typeof error !== "string" && (error.status === 401 || error.status === 403)) {
        employeeAuthorizationStore.logOut()
    }
})

export default fetcher
